import { App, Button, DatePicker, Flex, Form, Input, Modal, Select, Space, Table, Tag, Upload } from "antd";
import { useContext, useEffect, useState } from "react";
import user_api, { USER_ROLE } from "../api/users";
import { useForm } from "antd/es/form/Form";
import Search from "antd/es/input/Search";
import { project_api } from "../api/projects";
import dayjs from "dayjs";
import { Global } from "../main";
import { api_urls } from "../api/urls";
import storage from "../storage";
import { UploadOutlined } from "@ant-design/icons";

export function Project() {
    const [searchLoading, setSearchLoading] = useState(false)
    const [projectPage, setProjectPage] = useState({ total: 0, content: [] })
    const [projectReq, setProjectReq] = useState({ keyword: '', page: 1, size: 15 })
    const [updateProjectModalOpen, setUpdateProjectModalOpen] = useState(false)
    const [createProjectModalOpen, setCreateProjectModalOpen] = useState(false)
    const [createProjectForm] = useForm();
    const [updateProjectForm] = useForm();
    const { message, modal } = App.useApp();
    const [currentProject, setCurrentProject] = useState(null);
    const [uploadLoading, setUploadLoading] = useState(false);
    const { role } = useContext(Global)
    const columns = [
        {
            title: '项目名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '备注',
            dataIndex: 'remarks',
            key: 'remarks',
        },
        {
            title: '截止日期',
            key: 'deadline_time',
            render: (_, row) => (
                row.deadline_time ? dayjs(row.deadline_time).format("YYYY-MM-DD") : ''
            )
        },
        {
            title: '操作',
            key: 'action',
            fixed: 'right',
            width: 150,
            render: (_, row) => (<Space size={'middle'}>
                <Button type="link" onClick={() => {
                    updateProjectForm.setFieldsValue({ ...row, deadline_time: row.deadline_time ? dayjs(row.deadline_time) : null });
                    console.log(row)
                    setCurrentProject(row);
                    setUpdateProjectModalOpen(true)
                }} disabled={role === USER_ROLE.READONLY}>编辑</Button>
                <Button type="link" danger onClick={() => modal.confirm({
                    title: "删除项目",
                    content: `确认要删除项目：${row.name}吗？删除项目将删除对应项目下所有数据！`,
                    onOk: () => {
                        project_api.deleteProject(row.id).then(() => {
                            reFreshProject();
                        }).catch(e => message.error(e.response.data))
                    },
                    okText: '确定',
                    cancelText: '取消'
                })} disabled={role === USER_ROLE.READONLY}>删除</Button>
            </Space>)
        },
    ];
    const reFreshProject = (ur) => {
        let request = projectReq;
        if (!!ur) {
            request = ur;
        }
        project_api.pageProject(request).then(data => {
            setProjectPage({ ...data, content: data.content.map(it => ({ ...it, key: it.id })) })
            setSearchLoading(false)
        }).catch(e => message.error(e))
    }

    useEffect(() => {
        reFreshProject()
    }, []);

    return <>
        <Space style={{ margin: '10px' }}>
            <Search size="large" placeholder="输入关键字进行搜素" style={{ maxWidth: '30vw' }} loading={searchLoading} onSearch={(value) => {
                setSearchLoading(true)
                setProjectReq({ ...projectReq, keyword: value })
                reFreshProject({ ...projectReq, keyword: value })
            }}></Search>
            <Button size="large" type="primary" onClick={() => {
                setCurrentProject(null)
                createProjectForm.setFieldsValue(null)
                createProjectForm.resetFields();
                setCreateProjectModalOpen(true)
            }} disabled={role === USER_ROLE.READONLY}>创建</Button>
            <Upload name="file" action={api_urls.project.upload} showUploadList={false} loading={uploadLoading} headers={{
                token: storage.getUser()?.token
            }}
                beforeUpload={(file) => {
                    const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
                    if (!isExcel) {
                        message.error(`只能导入excel文件!`);
                    }
                    return isExcel || Upload.LIST_IGNORE;
                }}
                onChange={info => {
                    if (info.file.status !== 'uploading') {
                        setUploadLoading(true)
                    }
                    if (info.file.status === 'done') {
                        setUploadLoading(false)
                        message.success(`导入成功`);
                        reFreshProject({ ...projectReq, keyword: value })
                    } else if (info.file.status === 'error') {
                        setUploadLoading(false)
                        message.error(`导入失败`);
                    }
                }}>
                <Button disabled={role === USER_ROLE.READONLY} type="primary" size="large" icon={<UploadOutlined></UploadOutlined>}>导入老项目</Button>
            </Upload>
        </Space>
        <Table size="small" pagination={{
            position: ["bottomLeft"],
            pageSizeOptions: [projectReq.size],
            total: projectPage.total,
            current: projectReq.page,
            pageSize: projectReq.size,
            onChange: (page, pageSize) => {
                setProjectReq({ ...projectReq, page: page, size: pageSize });
                reFreshProject({ ...projectReq, page: page, size: pageSize })

            }
        }} dataSource={projectPage.content} columns={columns}></Table>
        <Modal maskClosable={false} title="编辑项目" okText="确定" cancelText="取消" onOk={() => {
            updateProjectForm.validateFields().then(data => {
                project_api.updateProject({ ...data, deadline_time: data.deadline_time ? data.deadline_time.valueOf() : null }).then(() => {
                    reFreshProject();
                    setUpdateProjectModalOpen(false)
                }).catch(e => message.error(e.response.data || "系统异常"))
            });

        }} onCancel={() => setUpdateProjectModalOpen(false)} open={updateProjectModalOpen}>
            <Form labelCol={{ span: 6 }} value={currentProject} wrapperCol={{ span: 18 }} form={updateProjectForm} initialValues={currentProject}>
                <Form.Item label="索引" name={"id"} hidden>
                    <Input />
                </Form.Item>
                <Form.Item label="项目名称" name={"name"} rules={[{
                    required: true,
                    message: '请输入项目名称'
                }]}>
                    <Input></Input>
                </Form.Item>
                <Form.Item label="备注" name={"remarks"}>
                    <Input.TextArea></Input.TextArea>
                </Form.Item>
                <Form.Item label='截止日期' name={'deadline_time'}>
                    <DatePicker />
                </Form.Item>
            </Form>
        </Modal>
        <Modal maskClosable={false} title="新建项目" okText="确定" cancelText="取消" onOk={() => {
            createProjectForm.validateFields().then(data => {
                project_api.createProject({ ...data, deadline_time: data.deadline_time ? data.deadline_time.valueOf() : null }).then(() => {
                    reFreshProject();
                    setCreateProjectModalOpen(false)
                }).catch(e => {
                    message.error(e.response.data || '系统异常')
                })
            });

        }} onCancel={() => setCreateProjectModalOpen(false)} open={createProjectModalOpen}>
            <Form labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} form={createProjectForm} initialValues={currentProject}>
                <Form.Item label="项目名称" name={"name"} rules={[{
                    required: true,
                    message: '请输入项目名称'
                }]}>
                    <Input></Input>
                </Form.Item>
                <Form.Item label="备注" name={"remarks"}>
                    <Input.TextArea></Input.TextArea>
                </Form.Item>
                <Form.Item label='截止日期' name={'deadline_time'}>
                    <DatePicker />
                </Form.Item>
            </Form>
        </Modal>
    </>
}